﻿namespace HZY.Repository.Admin;

/// <summary>
/// 程序启动器
/// </summary>
[ImportStartupModule<CoreEntityFrameworkStartup>]
public class AdminRepositoryStartup : StartupModule<AdminRepositoryStartup>
{
    /// <summary>
    /// 程序启动器
    /// </summary>
    /// <param name="webApplicationBuilder"></param>
    public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
    {
        var configuration = webApplicationBuilder.Configuration;
        var services = webApplicationBuilder.Services;
        var webHostEnvironment = webApplicationBuilder.Environment;

        var repositoryOptions = new AdminRepositoryOptions();

        if (repositoryOptions.DefaultDatabaseType == DefaultDatabaseType.PostgreSql)
        {
            //EnableLegacyTimestampBehavior 启动旧行为，避免时区问题，存储时间报错
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
        }

        services
            .AddDbContextFactory<AdminDbContext>()
            .AddEntityFrameworkRepositories<AdminDbContext>(repositoryOptions, (auditOptions) => { },
                (freeSqlOptions) =>
                {
                    freeSqlOptions.FreeSqlAuditAopList?.Add(new FreeSqlAuditAop());
                    freeSqlOptions.FreeSqlAction = (freeSql) =>
                    {
                        freeSql.Aop.CurdAfter += (object? sender, FreeSql.Aop.CurdAfterEventArgs curdAfter) =>
                        {
                            //var stringBuilder = new StringBuilder();
                            //stringBuilder.Append($"\r\n====[FreeSql 开始 耗时: {curdAfter.ElapsedMilliseconds} ms]=========");
                            //stringBuilder.Append($"\r\n{curdAfter.Sql}");
                            //stringBuilder.Append($"\r\n====[FreeSql 结束 线程Id:{Environment.CurrentManagedThreadId}]=========");
                            //LogUtil.Log.Warning(stringBuilder.ToString());
                            //Console.WriteLine(stringBuilder.ToString());
                        };
                    };
                });
    }

    /// <summary>
    /// Configure
    /// </summary>
    /// <param name="webApplication"></param>
    public override void Configure(WebApplication webApplication)
    {
        // 使用 DbContext

        #region 开发环境检测是否需要数据库迁移

        //if (webApplication.Environment.IsDevelopment())
        //{
        //    // 自动迁移 （如果迁移文件有变动）
        //using var scope = webApplication.Services.CreateScope();
        //using var adminDbContext = scope.ServiceProvider.GetService<AdminDbContext>();
        //if (adminDbContext!.Database.GetPendingMigrations().Count() > 0)
        //{
        //    try
        //    {
        //        adminDbContext.Database.Migrate();
        //    }
        //    catch (Exception ex)
        //    {
        //        //LogUtil.Log.Error(ex.Message, ex);
        //    }
        //}
    }

    #endregion
}